//
//  WBUserAccount.swift
//  WeiBoAPP
//
//  Created by 张学飞 on 2019/2/27.
//  Copyright © 2019 zxf. All rights reserved.
//

import UIKit
import YYModel

private let accoutFile:String = "useraccount.json"

class WBUserAccount: NSObject {

    var access_token:String?
    var uid:String?
    //过期时间
    var expiresDate:Date?

    var expires_in:TimeInterval = 0 {
        
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    override init() {
        super.init()
        
        guard let path = NSHomeDirectory().appending(accoutFile) as? String,
        let data = NSData(contentsOfFile: path)
            else {
                return
        }
        let dic = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:AnyObject]
        
        NSObject.yy_modelSet(with: dic as! [AnyHashable : Any])

        print("沙盒信息，\(self)")
        
        //判断过期
        expiresDate = Date(timeIntervalSinceNow: -3600 * 24) //晚一小时
        if expiresDate?.compare(Date()) != ComparisonResult.orderedDescending {
            print("账号过期")
         //清空
            access_token = nil
            uid = nil
            try? FileManager.default.removeItem(atPath: path)
            
        }else{
            print("账号正常")
        }
        
        
        
    }
    
    override var description: String {
        return yy_modelDescription()
    }
    
    
    
    
    
    
    //保存方法
    /**
     偏好设置（小）
     沙盒 归档 plist json
     数据库 fmdb
     钥匙串访问 小/自动加密  使用sskeychain
     
     */
    
    func saveAccount ()  {
//        var  dict = self.yy_modelToJSONObject() as? [String:AnyObject] ?? [:]
//        dict.removeValue(forKey: "expires_in")
//        //序列化
//        guard  let data = try? JSONSerialization.data(withJSONObject: dict,
//                                               options:[]),
//            let fileName:String = NSHomeDirectory().appending(accoutFile) as? String
//            
//        else {
//            return
//        }
//       
//        //写入磁盘
//        (data as NSData).write(toFile: fileName , atomically: true)
//        print("保存成功  \(fileName)")

    }
    
}
